var WxParse = require('../../../template/wxParse/wxParse.js');
var Api = require('../../../config/api.js');
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    articleDB:null,
    //是否显示广告
    showAd:1,
    showCollect:1,
    title:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let showCollect = options.showCollect;
    let showAd = options.showAd;
    let url = options.url;
    let title = options.title;
    let _id = options._id;

    //控制是否显示“收藏”
    console.info("======showCollect===" + showCollect);
    if (null != showCollect && "" != showCollect)
    {
      this.setData({
        showCollect: showCollect
      });
    }

    if (null != title && "" != title)
    {
      this.setData({
        title: title
      });
    }

    //在每段文章后台，都添加自已的广告信息
    if (0!=showAd)
    {
      wx.request({
        url: Api.adUrl,
        success: function (res2) {

          var html2 = res2.data.data.file.data;
          WxParse.wxParse('linkData', 'html', html2, that, 5);
        },
        fail: function (error) {
        },
      })
    }
    

    
    console.info("====url==" + url);
    //传了url就用url来解析文章
    if(null != url && ""!=url)
    {
      wx.showLoading({
        title: '加载中',
        icon: 'none'
      });
      wx.request({
        url: url,
        success: function (res) {
          wx.hideLoading();
          var html = res.data.data.file.data;
          WxParse.wxParse('article', 'html', html, that, 5);
        },
        fail: function (error) {
        },
      })
    }else
    {
      //没传url就用 articel来的content 来解析文章
      db.collection('article_list').doc(_id).get({
        success(res) {
          let article = res.data;
          that.setData({
            articleDB: article
          });
          if (article.content) {
            WxParse.wxParse('article', 'html', article.content, that, 5);
          }
        }
      })
    }
  },

  //收藏文章
  collectArticle: function () {
    let articleDB = this.data.articleDB;
    try {
      let myArticleList = wx.getStorageSync('my_article');
      if (!myArticleList) {
        myArticleList = new Array();
      }

      //如果
      if (this.array_contain(myArticleList, articleDB)) {
        wx.showToast({
          icon: "none",
          title: '您已经收藏过该文章'
        })
      } else {
        //删除content
        delete articleDB["content"];
        myArticleList.push(articleDB);
        wx.showToast({
          icon: "none",
          title: '收藏成功'
        })
      }
      wx.setStorageSync('my_article', myArticleList);

    } catch (e) {

    }   
  },

  array_contain: function (array, obj) {
    for (var i = 0; i < array.length; i++) {
      if (array[i]._id == obj._id)
        return true;
    }
    return false;
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})